package com.lzq.model.singleton.serializable;

import java.io.*;

/**
 * @author : modify
 * @version : v1.0
 * @description :
 * @createTime : 2022/11/14 10:11
 * @updateUser : modify
 * @updateTime : 2022/11/14 10:11
 * @updateRemark : 序列化问题
 */
public class Singleton implements Serializable {
    private static Singleton singleton = new Singleton();

    private static class SingletonHolder {
        private static final Singleton INSTANCE = new Singleton();
    }

    public static Singleton getInstance() {
        return SingletonHolder.INSTANCE;
    }

    public Object readResolve() {
        return SingletonHolder.INSTANCE;
    }
}

class Test {
    public static void main(String[] args) throws Exception {
        Test.writeObject2File();
        Test.readObjectFromFile();
        Test.readObjectFromFile();
    }

    private static Singleton readObjectFromFile() throws Exception {
        //创建对象输入流对象
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("D:\\data\\a.txt"));
        //第一个读取Singleton对象
        Singleton instance = (Singleton) ois.readObject();
        System.out.println(instance);
        return instance;
    }


    public static void writeObject2File() throws Exception {
        //获取Singleton类的对象
        Singleton instance = Singleton.getInstance();
        //创建对象输出流
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("D:\\data\\a.txt"));
        //将instance对象写出到文件中
        oos.writeObject(instance);
    }
}